from sqlalchemy import Column
from sqlalchemy.types import CHAR, Boolean,VARCHAR
from sqlalchemy.orm import relationship
from db import BaseModel


class User(BaseModel):
    __tablename__ = 'user'
    id = Column(CHAR(36), primary_key=True)
    access_key = Column(CHAR(50))
    secret_key = Column(CHAR(50))
    permission = Column(VARCHAR(500))
    is_superuser = Column(Boolean, default=False)
    pools = relationship('Pool', uselist=True, secondary='pool_and_user',backref='user',cascade="save-update, merge, delete")

    def __init__(self, access_key, secret_key, permission, is_superuser=False):
        import uuid
        self.access_key = access_key
        self.secret_key = secret_key
        self.permission = permission
        self.is_superuser = is_superuser
        self.id = unicode(uuid.uuid4())

    @classmethod
    def create(cls, keys):
        keys = keys.split(':')
        return cls(access_key=keys[0], secret_key=keys[1], permission=keys[2], is_superuser=keys[3])

    def __repr__(self):
        return '<User {0} access_key is {1} secret_key is {2}>'.format(self.id, self.access_key, self.secret_key)

    def add_pools(self, pools):
        pools = pools.split(',')
        me_pools = self.pools.split(',')
        for pool in pools:
            me_pools.append(pool)
        self.pools = ','.join(me_pools)

    def del_pools(self, pools):
        pools = pools.split(',')
        me_pools = self.pools.split(',')
        for pool in pools:
            if pool in me_pools:
                me_pools.remove(pool)
        self.pools = ','.join(me_pools)
